package com.sheep.jucdemo.part2.part2_9;



import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Date 2022/4/13 20:30
 * @Created by sheep
 */
public class Test2_9_3 {

    // 获取Unsafe的实例
    static final Unsafe unsafe;

    // 记录变量state在类Test2_9_2中的偏移量
    static final long stateOffset;

    // 变量
    private volatile long state = 0;

    static {
        try {
            // 使用反射获取Unsafe的成员变量theUnsafe
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            // 设置为可存取
            field.setAccessible(true);
            // 获取state在Test2_9_3中的偏移量
            unsafe = (Unsafe) field.get(null);
            stateOffset = unsafe.objectFieldOffset(Test2_9_3.class.getDeclaredField("state"));
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            throw new Error(e);
        }
    }

    public static void main(String[] args) {

        // 创建实例，并且设置state值为1
        Test2_9_3 test = new Test2_9_3();
        // 如果test对象中内存偏移量stateOffset的state变量的值为0，则更新值为1
        boolean success = unsafe.compareAndSwapInt(test, stateOffset, 0, 1);
        System.out.println(success);
    }
}
